package com.example.shangguigu.rsa_ecc;


import sun.misc.BASE64Decoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.security.KeyFactory;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;

/**
 * @DESCRIPTION:
 * @USER: shg
 * @DATE: 2023/2/25 15:00
 */
public class RsaDemo_My {

    /**
     * 公钥加密
     *
     * @param input           待加密数据
     * @param base64PublicKey base64编码的RSA公钥
     * @throws Exception
     */
    private static String rsaEncrypt(String input, String base64PublicKey) throws Exception {
        byte[] bytes = new BASE64Decoder().decodeBuffer(base64PublicKey);
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        // 当长度过长的时候，需要分割后加密 117个字节
        byte[] resultBytes = getMaxResultEncrypt(input, cipher);

        return Base64.getEncoder().encodeToString(resultBytes);
        // return new BASE64Encoder().encode(resultBytes);
    }

    /**
     * 私钥解密
     *
     * @param input            加密后的字符串
     * @param base64PrivateKey base64编码的私钥
     * @return 解密后的明文
     * @throws Exception
     */
    private static String rsaDecrypt(String input, String base64PrivateKey) throws Exception {
        byte[] privateBytes = new BASE64Decoder().decodeBuffer(base64PrivateKey);
        RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateBytes));

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return new String(getMaxResultDecrypt(input, cipher));
    }

    private static byte[] getMaxResultDecrypt(String str, Cipher cipher) throws Exception {
        byte[] inputArray = Base64.getDecoder().decode(str);
        int inputLength = inputArray.length;
        // 最大解密字节数，超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 128;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

    private static byte[] getMaxResultEncrypt(String str, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
        byte[] inputArray = str.getBytes();
        int inputLength = inputArray.length;
        // 最大加密字节数，超出最大字节数需要分组加密
        int MAX_ENCRYPT_BLOCK = 117;
        // 标识
        int offSet = 0;
        byte[] resultBytes = {};
        byte[] cache = {};
        while (inputLength - offSet > 0) {
            if (inputLength - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(inputArray, offSet, MAX_ENCRYPT_BLOCK);
                offSet += MAX_ENCRYPT_BLOCK;
            } else {
                cache = cipher.doFinal(inputArray, offSet, inputLength - offSet);
                offSet = inputLength;
            }
            resultBytes = Arrays.copyOf(resultBytes, resultBytes.length + cache.length);
            System.arraycopy(cache, 0, resultBytes, resultBytes.length - cache.length, cache.length);
        }
        return resultBytes;
    }

    /**
     * ras加解密测试
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {

        String sourceData = "sunhongguang";

        // 公钥
        String publicKey_my = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwCatefCcMklTYcfv/FVB8Q3vk03CNwif9de5Hy3xLHgXdSeH+0vbftj4wXz5C4H/cOxwXJiUcNXkLPFFIJVS+fLzdeHM7TB7BxEtGnY4O2kZBioolf2qSnlqTDyIYde8KtnmfDgpPxUGZV5befwZRgo244ygWB7FO731NcipZBwIDAQAB";
        // 私钥
        String privateKey_my = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALAJq158JwySVNhx+/8VUHxDe+TTcI3CJ/117kfLfEseBd1J4f7S9t+2PjBfPkLgf9w7HBcmJRw1eQs8UUglVL58vN14cztMHsHES0adjg7aRkGKiiV/apKeWpMPIhh17wq2eZ8OCk/FQZlXlt5/BlGCjbjjKBYHsU7vfU1yKlkHAgMBAAECgYAUFtZmrvZp2d0y4jcm0hDgTXc7EuIaW1ji9O1fZhpmHCQBL+hJg1vHBe4s6QGa8jHFOT2oaqL7iCKrJJQGDrSP49f7/RJiR5EU6IHSRHowK/cUzgZ57/9ROVRva46DQPxEzcGlRTgOI7ajjIVmBDW03XN5+bCITiGh/HFmjKAEYQJBAOhSCENxWi6eBI11aQpuywwRJBNgAaPQqGzrfJQ8xPsWYV8d+U8QzH55IR9+egtrbvW0t4Xdu96iwnSn0Si4IXcCQQDB+wvM+N10VHbr6sDHGcQXWLioK9GN/rZQUgBnC5EKhcQBQZkevJtY92OKCq6sgN5EIhqwNdleFHdkXclNOejxAkBUXGVvyBuNTggtLfNkvHKzAQ5ukrBFwiFG3AQy+BY3bxsQpRvA4ELBsk6a1xyORQbX5jW2QJxV7hhasA29kY9lAkAHeUGqIwh9O+fdDQ1iXmbEs4Fh0VZgjyi9DXvAfJyY+DBmD/3zRjcCBX4LSoASW2C05U977Ic0bbtv3YEs/YcxAkANyGSIAH5PS1aUSLMD9NC9Yov+9AyJJY5P5CePwm1bDGcrq1kNQzUW3uYIL26u9D9wHdP7Ownj+XSshPc3ynk0";

        // 公钥加密
        String rsaEncrypt = rsaEncrypt(sourceData, publicKey_my);
        System.out.println("rsa公钥加密后的结果如下： \n"+rsaEncrypt);
        // 私钥解密
        String rsaDecrypt = rsaDecrypt(rsaEncrypt, privateKey_my);
        System.out.println("\nrsa私钥解密后的结果如下： \n"+rsaDecrypt);
    }


}
